package model

import (
	"encoding/json"
	"strconv"
	"time"
	"zimuzu_cvn_web_api/config"
	. "zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
)

//支付网关通用响应数据结构
type GatewayResponse struct {
	Status int    `json:"status"`
	Info   string `json:"info"`
	Data   CoboResponse
}

//COBO通用响应数据结构
type CoboResponse struct {
	Success          bool   `json:"success"`
	ErrorCode        int    `json:"error_code"`
	ErrorDescription string `json:"error_description"`
	ErrorMessage     string `json:"error_message"`
	Result           CoboTransaction
}

//COBO交易数据结构
type CoboTransaction struct {
	Id            string       `json:"id"`
	Coin          string       `json:"coin"`
	DisplayCode   string       `json:"display_code"`
	Description   string       `json:"description"`
	Decimal       int64        `json:"decimal"`
	Address       string       `json:"address"`
	SourceAddress string       `json:"source_address"`
	Side          string       `json:"side"`
	Amount        string       `json:"amount"`
	AbsAmount     string       `json:"abs_amount"`
	TxId          string       `json:"txid"`
	VoutN         int64        `json:"vout_n"`
	RequestId     string       `json:"request_id"`
	Status        string       `json:"status"`
	CreatedTime   int64        `json:"created_time"`
	LastTime      int64        `json:"last_time"`
	ConfirmedNum  int64        `json:"confirmed_num"`
	TxDetail      CoboTxDetail `json:"tx_detail"`
}

//COBO交易详情数据结构
type CoboTxDetail struct {
	BlockNum int64 `json:"blocknum"`
}

//向支付网关发送HTTP请求
func GatewayRequest(method string, api string, params map[string]string, headers map[string]string) (res GatewayResponse, err error) {
	var sign string
	t := strconv.FormatInt(time.Now().Unix(), 10)
	paramStr := SortParams(params)
	if method == "GET" {
		sign = CreateGateWaySign(t, "")
	} else {
		sign = CreateGateWaySign(t, paramStr)
	}
	api = config.C.Domains.PaymentGateway + api + "?t=" + t + "&sign=" + sign
	body, err := HttpRequest(method, api, params, headers)
	if err != nil {
		Log("err", err)
		return res, err
	}
	err = json.Unmarshal(body, &res)
	if err != nil {
		Log("err", "JSON解析失败：", err)
		err = errno.GetDataErr
		return res, err
	}
	if res.Status != 1 {
		Log("err", "支付网关报错：", res.Info)
		err = errno.GetDataErr
		return res, err
	}
	if !res.Data.Success {
		Log("err", "COBO报错：", res.Data.ErrorMessage)
		err = errno.GetDataErr
		return res, err
	}
	return res, nil
}
